#include"Bullet.h"
#define bullet_speed 1.0f
#define bullet_jump 0.1f
#define bullet_fall 0.05f
CBullet::CBullet(int _x,int _y,int _direction)                                                  
{	x=_x;
	y=_y;
	vx=bullet_speed;
	vy=0;
	isactive=true;
	isexplose=false;
	bejump=false;
	direction=_direction;
	bullet=new CSprite(false,0,0,15,13,0,3,0);
	explose=new CSprite(true,0,16,18,18,0,0,0);
}
CBullet::~CBullet()
{
	if(bullet!=NULL) delete bullet;
	if(explose!=NULL) delete explose;
}
void CBullet::Move(CStaticObjects *StaticObject, RECT screen)
{
	if(isexplose==true) return;
	RECT bulletRect=bullet->getRECT(x,y);
	RECT objectRect;
	int kq=0;
	bulletRect.bottom=bulletRect.bottom-10;
	bulletRect.left-=5;
	bulletRect.right+=5;
	StaticObject->tree->Collision(StaticObject->tree->root,screen,bulletRect,&kq,&objectRect);
	if(kq!=0)
	{
		isexplose=true;
	}
	bulletRect=bullet->getRECT(x,y);
	bulletRect.bottom+=5;
	bulletRect.left+=3;
	bulletRect.right-=3;
	StaticObject->tree->Collision(StaticObject->tree->root,screen,bulletRect,&kq,&objectRect);
	if(kq!=0)
	{
		bejump=true;
	}
	else bejump=false;
}
bool CBullet::CollisionWithEnemies(CEnemies *Enemies)
{
	if(isactive==false) return false;
	RECT bulletRect=bullet->getRECT(x,y);
	RECT dest;
	RECT enemiesRect;
		NODE_KOOPA *q;
	bulletRect=bullet->getRECT(x,y);
	q=Enemies->list_koopa.pHead;
	while(q!=NULL)
	{
		enemiesRect=q->koopa->getRECT();
		if(IntersectRect(&dest,&bulletRect,&enemiesRect))
		{
			q->koopa->BeFired();
			if(direction==0) q->koopa->touch_left=false;
			else q->koopa->touch_left=true;
			isexplose=true;
			return true;
		}
		q=q->next;
	}

	NODE_GOOMBA *p;
	p=Enemies->list_goomba.pHead;
	while(p!=NULL)
	{
		if(p->goomba->beJump==true||p->goomba->bePushed==true) return false;
		enemiesRect=p->goomba->getRECT();
		if(IntersectRect(&dest,&bulletRect,&enemiesRect))
		{
			p->goomba->beJump=true;
			if(direction==0) p->goomba->touch_left=false;
			else p->goomba->touch_left=true;
			isexplose=true;
			return true;
		}
		p=p->next;
	}
	NODE_PIRANA *tam;
	tam=Enemies->list_pirana.pHead;
	while(tam!=NULL)
	{
		enemiesRect=tam->pirana->getRECT();
		if(IntersectRect(&dest,&bulletRect,&enemiesRect))
		{
			tam->pirana->isover=true;
			isexplose=true;
			return true;
		}
		tam=tam->next;
	}
	return false;
}
void CBullet::Render(LPD3DXSPRITE sprite, LPDIRECT3DTEXTURE9 image, int time, int xcamara)
{
		if(isactive==true)
		{
		if(direction==0) vx=bullet_speed;
		else vx=-bullet_speed;
		if(bejump==true)
		{
			vy=-bullet_jump;
		}
		else vy=bullet_fall;
		if(isexplose==true)
		{
			vx=vy=0;
		}
		x+=vx*time;
		y+=vy*time*time;
		if(isexplose==true) 
		{
			explose->Render(sprite,image,x-xcamara,y);
			isactive=false;
		}
		else
		{
		bullet->Next();
		bullet->Render(sprite,image,x-xcamara,y);	
		}
		}
}